﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace Cms.Web.Framework.Infrastructure
{
    public class ImageResizer
    {
        
        public static Size CalculateNewSize(Size originalSize, Size maxSize)
        {
            double aspectRatio = (double)originalSize.Width / (double)originalSize.Height;
            double boxRatio = (double)maxSize.Width / (double)maxSize.Height;
            double scaleFactor = originalSize.Width < maxSize.Width && originalSize.Height < maxSize.Height
                                     ? 1
                                     : (boxRatio > aspectRatio
                                            ? (double) maxSize.Height/(double) originalSize.Height
                                            : (double) maxSize.Width/(double) originalSize.Width);
            int newWidth = (int)Math.Round(originalSize.Width * scaleFactor, 0);
            int newHeight = (int)Math.Round(originalSize.Height * scaleFactor, 0);
            if (newWidth == 0)
                newWidth = 1;
            if (newHeight == 0)
                newHeight = 1;
            return new Size(newWidth, newHeight);
        }

        private static Image CreateResizedImage(Image original, Size newSize)
        {
            Image img = new Bitmap(newSize.Width, newSize.Height);
            using (Graphics g = Graphics.FromImage(img))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.DrawImage(original, 0, 0, newSize.Width, newSize.Height);
            }
            return img;
        }

        public static Image Resize(Image original, Size maxSize)
        {
            Size newSize = CalculateNewSize(new Size(original.Width, original.Height), maxSize);
            return CreateResizedImage(original, newSize);  
        }
    }
}